package com.kvest.scanrecognizer.utility;

import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 30.08.13
 * Time: 21:57
 * To change this template use File | Settings | File Templates.
 */
public class FileUtility {
    public static String getFileName(String filePath, boolean withExtension) {
        File file = new File(filePath);
        if (withExtension) {
            return file.getName();
        } else {
            String name = file.getName();
            int pos = name.lastIndexOf(".");
            if (pos > 0) {
                name = name.substring(0, pos);
            }
            return name;
        }
    }

    public static String fileToBase64(File file) {
        try {
            InputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }

            String result = Base64.encodeToString(output.toByteArray(), Base64.NO_WRAP);

            return result;
        } catch (Exception exception) {
            return "";
        }
    }

    public static boolean createDirIfNotExists(String path) {
        File file = new File(Environment.getExternalStorageDirectory(), path);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Log.e("FileUtility", "Problem creating \"" + path + "\" folder");
                return false;
            }
        }

        return true;
    }
}
